<!-- 模块参数 -->
<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="flex aic">
                <ElButton type="primary" :icon="Plus" @click="onAdd">
                    新增模块参数
                </ElButton>
            </div>
            <div class="">
                <ElInput v-model="state.searchData.configName" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入参数名称" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    {{ t('common.query') }}
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    {{ t('common.reset') }}
                </ElButton>

            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
                :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title">
        <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            status-icon>
            <div class="flex jcsb">
                <el-form-item label="参数名称" prop="configName">
                    <el-input v-model="state.ruleForm.configName" placeholder="请输入参数名称" />
                </el-form-item>
                <el-form-item label="参数主键" prop="configKey">
                    <el-input v-model="state.ruleForm.configKey" placeholder="请输入参数主键" />
                </el-form-item>
                <el-form-item label="参数状态" prop="configValue">
                    <!-- <el-input v-model="state.ruleForm.configValue" placeholder="请输入参数状态" /> -->
                    <ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" v-model="state.ruleForm.configValue" />
                </el-form-item>
            </div>
            <el-form-item label="备注" prop="remark">
                <!-- <Editor /> -->
                <el-input v-model="state.ruleForm.remark" placeholder="请输入备注" :autosize="{ minRows: 2 }" type="textarea"
                    row="4" />
            </el-form-item>
            <el-form-item>
                <div class="flex jcfe w-[100%]">
                    <el-button type="primary" v-loading="loadingAdd" @click="submitForm(ruleFormRef)">保存</el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </Dialog>
</template>
    
<script setup lang="tsx">
import { Editor } from "@/components/Editor/index"
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox, ElSwitch } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { formatToDateTime } from "@/utils/dateUtil"
import type { FormInstance, FormRules } from 'element-plus'
import { getConfigApi, addConfigApi, editConfigApi, deleteConfigApi } from "@/api/module/index"
import { useRouter } from 'vue-router'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useStorage } from '@/hooks/web/useStorage'
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const { push } = useRouter()
const props = { multiple: true }
interface RuleForm {
    configName: string
    configKey: string
    status: string
    remark: string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    configName: [
        { required: true, message: '请输入参数名称', trigger: 'blur' },
    ],
    configKey: [
        { required: true, message: '请输入参数主键', trigger: 'blur' },
    ]
})
const loadingAdd = ref(false)
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            if (state.dialogVisible1title == '新增参数模块') {
                addConfigApi(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            } else {
                let obj = {
                    configId: state.ruleForm.configId,
                    configName: state.ruleForm.configName,
                    configKey: state.ruleForm.configKey,
                    configValue: state.ruleForm.configValue,
                    remark: state.ruleForm.remark,
                }
                editConfigApi(obj).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    if (!formEl) return
    formEl.resetFields()
}
const { t } = useI18n()
const dialogVisible1 = ref(false)//定义职位详情弹框
const state = reactive({
    fileList: [] as any,
    react: true,//分页刷新
    dialogVisible1title: "新增模块参数",
    ruleForm: {} as any,
    searchData: {
        configName: "",
    },//搜索参数
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'configName',
        label: t('参数名称'),
    },
    {
        field: 'configKey',
        label: t('参数键值'),
    },
    {
        field: 'createTime',
        label: t('创建时间'),
    },
    {
        field: 'remark',
        label: t('备注'),
    },
    {
        field: 'configValue',
        label: t('是否展示'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div ><ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" v-model={data[0].row.configValue} before-change={() => switchClicks(data[0].row)} /></div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                                {t('查看')}
                            </ElButton> */}
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>

                        </>
                    )
                }
            }
        }
    }
])

const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        const { currentPage, pageSize } = tableState
        const res: any = await getConfigApi({
            pageNum: state.react ? 1 : unref(currentPage),
            pageSize: unref(pageSize),
            configName: state.searchData.configName,
            isAsc:"desc",
            orderByColumn:"createTime"
        })
        res.rows.forEach(elements => {
            if (elements.configValue == 'true') {
                elements.configValue = true
            } else {
                elements.configValue = false
            }
        })
        console.log(res);
        state.react = false
        return {
            list: res.rows,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}

const switchClicks = (rows) => {
    let strings = rows.configValue == false ? "确定展示？" : "取消展示？"
    ElMessageBox.confirm(
        `${strings}`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let obj = {
                configId: rows.configId,
                configName: rows.configName,
                configKey: rows.configKey,
                configValue: !rows.configValue,
                remark: rows.remark,
            }
            editConfigApi(obj).then((res: any) => {
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
                getList()
                dialogVisible1.value = false
                loadingAdd.value = false
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
                loadingAdd.value = false
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)

// 新增
const onAdd = () => {
    state.ruleForm = {}
    state.ruleForm.configValue=false
    state.fileList = []
    dialogVisible1.value = true
    state.dialogVisible1title = t('新增参数模块')
}
const action = (row: any) => {
    console.log("详情", row);
    dialogVisible1.value = true
    state.ruleForm = row
    state.dialogVisible1title = t('编辑参数模块')
}
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该参数模块？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deleteConfigApi(row.configId).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })
}

// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.configName = ""
    state.react = true
    getList()
}

// api区域---------------------------------------------------------------------------


</script>
    
<style lang="less" scoped></style>